const axios = require('axios');

(async () => {
  console.log('🔍 详细调试分析...');
  
  try {
    // 1. 登录获取token
    const loginResponse = await axios.post('http://localhost:3000/api/auth/login', {
      email: 'alice@student.com',
      password: 'password123'
    });
    
    const authToken = loginResponse.data.token;
    const userId = loginResponse.data.user.id;
    console.log(`✅ 用户登录成功: ID=${userId}`);
    
    // 2. 获取第一个活动的详细信息
    const activitiesResponse = await axios.get('http://localhost:3000/api/activities?status=available');
    const activity = activitiesResponse.data.activities[0];
    
    console.log('\n📋 活动详细信息:');
    console.log(`- ID: ${activity.id}`);
    console.log(`- 标题: ${activity.title}`);
    console.log(`- 状态: ${activity.status}`);
    console.log(`- 当前参与人数: ${activity.current_participants}`);
    console.log(`- 最大参与人数: ${activity.max_participants}`);
    console.log(`- 开始时间: ${activity.start_time}`);
    console.log(`- 结束时间: ${activity.end_time}`);
    
    // 3. 获取活动详情（包含用户参与状态）
    const activityDetailResponse = await axios.get(`http://localhost:3000/api/activities/${activity.id}`, {
      headers: { Authorization: `Bearer ${authToken}` }
    });
    
    console.log('\n🔍 活动详情检查:');
    console.log('- 用户参与状态:', activityDetailResponse.data.activity.userParticipation || '未参与');
    console.log('- 参与者列表长度:', activityDetailResponse.data.activity.participants?.length || 0);
    
    // 4. 尝试参与活动并捕获详细错误
    console.log('\n📝 尝试参与活动...');
    try {
      const joinResponse = await axios.post(`http://localhost:3000/api/activities/${activity.id}/join`, {}, {
        headers: { Authorization: `Bearer ${authToken}` }
      });
      console.log('✅ 参与成功:', joinResponse.data);
    } catch (joinError) {
      console.log('❌ 参与失败:');
      console.log('- 状态码:', joinError.response?.status);
      console.log('- 错误信息:', joinError.response?.data);
      
      // 检查具体的错误原因
      if (joinError.response?.status === 400) {
        const errorMsg = joinError.response.data.error;
        console.log('📋 分析错误原因:');
        
        if (errorMsg.includes('已参与')) {
          console.log('  → 用户已经参与过此活动');
        } else if (errorMsg.includes('未开放')) {
          console.log('  → 活动未开放报名');
        } else if (errorMsg.includes('已开始')) {
          console.log('  → 活动已开始，无法报名');
        } else if (errorMsg.includes('已满')) {
          console.log('  → 活动人数已满');
        }
      }
    }
    
    // 5. 再次检查参与状态
    console.log('\n🔄 重新检查参与状态...');
    const updatedDetailResponse = await axios.get(`http://localhost:3000/api/activities/${activity.id}`, {
      headers: { Authorization: `Bearer ${authToken}` }
    });
    
    const participation = updatedDetailResponse.data.activity.userParticipation;
    console.log('📊 最新参与状态:', participation || '仍未参与');
    
    if (participation) {
      console.log(`   - 状态: ${participation.status}`);
      console.log(`   - 注册时间: ${participation.registered_at}`);
      console.log(`   - 签到时间: ${participation.attended_at || '未签到'}`);
    }
    
    // 6. 测试不同的活动（如果当前活动有问题）
    if (!participation && activitiesResponse.data.activities.length > 1) {
      console.log('\n🔄 尝试参与其他活动...');
      
      for (let i = 1; i < Math.min(3, activitiesResponse.data.activities.length); i++) {
        const testActivity = activitiesResponse.data.activities[i];
        console.log(`\n测试活动 ${testActivity.id}: ${testActivity.title}`);
        
        try {
          const testJoinResponse = await axios.post(`http://localhost:3000/api/activities/${testActivity.id}/join`, {}, {
            headers: { Authorization: `Bearer ${authToken}` }
          });
          console.log('✅ 成功参与:', testJoinResponse.data.message);
          break;
        } catch (testError) {
          console.log('❌ 失败:', testError.response?.data?.error);
        }
      }
    }
    
    // 7. 检查勋章系统
    console.log('\n🏆 检查勋章系统...');
    const allBadgesResponse = await axios.get('http://localhost:3000/api/badges');
    console.log('📈 总勋章数量:', allBadgesResponse.data.badges?.length || 0);
    
    if (allBadgesResponse.data.badges?.length === 0) {
      console.log('⚠️ 勋章系统问题: 系统中没有任何勋章');
    }
    
    // 8. 检查用户拥有的勋章
    const userBadgesResponse = await axios.get(`http://localhost:3000/api/badges?filter=owned`, {
      headers: { Authorization: `Bearer ${authToken}` }
    });
    console.log('🎖️ 用户拥有勋章:', userBadgesResponse.data.badges?.length || 0);
    
  } catch (error) {
    console.error('❌ 调试过程出错:', error.message);
    if (error.response) {
      console.error('响应详情:', error.response.data);
    }
  }
})(); 